<template>
  <div class="userUpdate">
    <h1>更换头像</h1>
    <div class="file">
      <form action="" enctype="multipart/form-data">
        <input type="file" @change="fileChange" ref="fil" />
      </form>
    </div>
    <div class="img">
      <img
        class="img-bg"
        src="https://music.163.com/style/web2/img/default/default_cover.png"
        alt=""
        v-if="bgVisible"
      />
      <img :src="imageUrl" alt="" />
    </div>
    <el-button type="primary" @click="updata">保存</el-button>
  </div>
</template>

<script>
import { updateImg } from '@/api/api.js'
export default {
  data() {
    return {
      imageUrl: '',
      bgVisible: true
    }
  },
  created() {},
  methods: {
    // 选择文件
    fileChange() {
      if (this.$refs.fil.files[0]) {
        let a = window.URL.createObjectURL(this.$refs.fil.files[0])
        // console.log(a)
        this.imageUrl = a
      } else {
        this.imageUrl = ''
      }

      // console.log(e)
    },
    // 保存
    async updata() {
      // console.log(this.formData)
      console.log(this.$refs.fil.files[0])
      var formData = new FormData()
      formData.append('imgFile', this.$refs.fil.files[0])
      const res = await updateImg(formData)
      console.log(res)
    }
  },
  watch: {
    imageUrl: function () {
      console.log(this.imageUrl)
      this.imageUrl === '' ? (this.bgVisible = true) : (this.bgVisible = false)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button {
  margin-top: 20px;
}
.userUpdate {
  width: 980px;
  background: #fff;
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 40px;
}
.file {
  // display: block;
  height: 32px;
  width: 96px;
}
.img {
  width: 322px;
  height: 322px;
  border: 1px solid #fff;
  position: relative;
  img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .img-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
  }
}
</style>
